package com.example.world.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.world.dao.CityDAO;
import com.example.world.domain.City;

@WebServlet("/city")
public class CityServlet extends HttpServlet 
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		// 1. 获取提交的参数
		int id= Integer.parseInt(req.getParameter("id"));
		
		// 2. 调用模型
		CityDAO dao = new CityDAO();
		
		String jsonStr = null;
		
		try {
			List<City> list = dao.findAll();
			
			jsonStr = JSONArray.toJSONString(list);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		id = 1;
		try {
			City c = dao.findByCode(id);
				
			jsonStr = JSONObject.toJSONString(c);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			pw.print(jsonStr);
	}
		

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}


// 练习:
// 实现城市的接口
// city				显示所有的json数组
// city?id=1		显示这个城市的json信息
// city?name=wuxi   显示名字为wuxi这个城市的json信息
// city?countryCode=chn 显示国家编号为chn的城市的json信息


